/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xstgongyi.eduaid.common.ControllerHelper;
import org.xstgongyi.eduaid.dataobject.SchoolYearDO;
import org.xstgongyi.eduaid.service.SchoolYearService;

/**
 * @author oldcrane<br/>
 * @created 2019-03-27
 */
@Controller
@RequestMapping("/school-years")
public class SchoolYearController {
	@Autowired
	private SchoolYearService schoolYearService;

	@GetMapping("/entry")
	public String entryPage(ModelMap map) {
		return "masterdata/school_year";
	}

	@GetMapping("")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(name = "active", required = false) Boolean active) {
		List<SchoolYearDO> schoolYearList = null;
		if (null == active) {
			schoolYearList = schoolYearService.listAll();
		} else {
			schoolYearList = schoolYearService.listByStatus(active);
		}
		return ControllerHelper.successResponse(schoolYearList);
	}

	@PostMapping("")
	@ResponseBody
	public Map<String, Object> add(@RequestBody SchoolYearDO schoolYear) {
		if (null == schoolYear) {
			return (ControllerHelper.errorResponse(1, "非法输入：要添加的学年参数为空对象。"));
		}
		schoolYearService.insert(schoolYear.getName(), schoolYear.getAbbrev(), schoolYear.getActive());
		return ControllerHelper.successResponse(null);
	}

	@GetMapping("/{id}")
	@ResponseBody
	public Map<String, Object> get(@PathVariable("id") Integer id) {
		SchoolYearDO schoolYear = schoolYearService.getById(id);
		if (null != schoolYear) {
			return ControllerHelper.successResponse(schoolYear);
		} else {
			return ControllerHelper.errorResponse(1, "School Year does not exist(id:" + id + ").");
		}
	}

	@PostMapping("/{id}")
	@ResponseBody
	public Map<String, Object> update(@PathVariable("id") Integer id, @RequestBody SchoolYearDO schoolYear) {
		if (null == schoolYear) {
			return (ControllerHelper.errorResponse(1, "非法输入：要添加的学年参数为空对象。"));
		}
		schoolYearService.update(id, schoolYear.getName(), schoolYear.getAbbrev(), schoolYear.getActive());
		return ControllerHelper.successResponse(null);
	}

}
